/*
 * @lc app=leetcode.cn id=567 lang=swift
 *
 * [567] 字符串的排列
 */

// @lc code=start
class Solution {
    func checkInclusion(_ s1: String, _ s2: String) -> Bool {
        let sArr = Array(s2)
        var need: [Character: Int] = [:]
        var window: [Character: Int] = [:]
        for c in s1 {
            need[c, default: 0] += 1
        }

        var left = 0, right = 0
        var matchCount = 0
        while right < sArr.count {
            let rChar = sArr[right]
            right += 1
            if let rCount = need[rChar] {
                window[rChar, default: 0] += 1
                if window[rChar] == rCount {
                    matchCount += 1
                }
            }

            while right - left >= s1.count {
                if matchCount == need.count {
                    return true
                }
                let lChar = sArr[left]
                left += 1
                if let lCount = need[lChar] {
                    if window[lChar] == lCount {
                        matchCount -= 1
                    }
                    window[lChar]! -= 1
                }
            }
        }
        return false;
    }
}
// @lc code=end

